package Review;

class Solution3 {
    //定义全局变量
    int m2,n2,k2;
    //定义访问状态
    boolean[][] sta;
    //定义遍历数组
    int[] dx = {-1,1,0,0};
    int[] dy = {0,0,-1,1};
    int ret;
    public int movingCount(int m, int n, int k) {
        m2 = m;
        n2 = n;
        k2 = k;
        sta = new boolean[m][n];
        dfs(0,0);
        return ret;
    }
    void dfs(int i,int j){
        ret++;
        sta[i][j] = true;
        for(int k = 0;k<4;k++){
            int x = i + dx[k];
            int y = j + dy[k];
            // if(x >= 0 && y < m2 && y >= 0 && y < n2 && !sta[x][y] && check(x,y)){
                if((x >= 0 && x < m2 && y >= 0 && y < n2 && !sta[x][y] && check(x, y))){
                dfs(x,y);
            }
        }
    }
    boolean check(int i,int j){
        int temp = 0;
        while(i != 0){
            temp+=i%10;
            i/=10;
        }
        while(j != 0){
            temp+=j%10;
            j/=10;
        }
        return temp <=k2;
    }
}